package com.zhangh.summer.admin.support.base;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @description: TODO
 * @author: zhanghui  zhanghlucky@163.com
 * @create: 2021-06-10 21:50
 **/

@Slf4j
@Data
public class JsonResponse {
    public boolean success;
    public String msg;
    public int code;
    public Object data;

    public JsonResponse(){
        this.success=true;
        this.msg="调用成功";
        this.code=200;
    }
    public JsonResponse(boolean success){
        if (success){
            code=200;
            msg="调用成功！";
        }else{
            code=500;
            msg="调用失败！";
        }
        this.success=success;
    }

    public JsonResponse(boolean success, String msg){
        if (success){
            code=200;
        }else{
            code=500;
        }
        this.success=success;
        if (StringUtils.isNotBlank(msg)){
            this.msg=msg;
        }else{
            this.msg="";
        }

    }

    public JsonResponse(boolean success, int code, String msg){
        this.success=success;
        this.code=code;
        this.msg=msg;
    }
    public JsonResponse success(){
        return new JsonResponse(true,200,"调用成功！");
    }

    public String toJson(){
        return toJson(null);
    }

    public String toJson(Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", success);
        jsonObject.put("msg",msg);
        jsonObject.put("code",code);
        Object obj=data;
        if (data instanceof String){//兼容已经是json的字符串
            String dataStr=data.toString();
            if (dataStr.startsWith("{")){
                try {
                    obj= JSONObject.parseObject(dataStr);
                }catch (Exception ignored){
                    log.error("parse dataStr error:{}",ignored.getMessage());
                    ignored.printStackTrace();
                }
            }else if (dataStr.startsWith("[")){
                try {
                    obj= JSONObject.parseArray(dataStr);
                }catch (Exception ignored){
                    log.error("parse dataStr array error:{}",ignored.getMessage());
                    ignored.printStackTrace();
                }
            }
        }
        jsonObject.put("data",obj);
        String jsonStr = JSONObject.toJSONString(jsonObject,
                SerializerFeature.WriteMapNullValue,//保留空的字段
                SerializerFeature.WriteNullStringAsEmpty,//String null -> ""
                SerializerFeature.WriteNullNumberAsZero,//Number null -> 0
                //SerializerFeature.WriteNullListAsEmpty,//List null-> []
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullBooleanAsFalse);//boolean -> false
        return jsonStr;
    }


}

